package com.youxue.teachin.main;

import java.util.ArrayList;
import java.util.List;

import android.app.TabActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.DrawableRes;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;
import com.Navigator;
import com.library.uiframework.utils.MToast;
import com.library.uiframework.utils.StringUtils;
import com.youxue.teachin.R;
import com.youxue.teachin.youmen.UMenUtils;

/**
 * 在此写用途
 *
 * @author: zhiwei
 * @date: 2017-10-08 14:35
 * @version: 9.1.0
 */
public class MainActivity extends TabActivity {
    private final static long READY_BACKGROUND_TIMEOUT = 3500;
    private long mLastReadyBackgroundTimeStamp;

    @Override
    public void onBackPressed() {
        if (mLastReadyBackgroundTimeStamp == 0
            || (System.currentTimeMillis() - mLastReadyBackgroundTimeStamp > READY_BACKGROUND_TIMEOUT)) {
            mLastReadyBackgroundTimeStamp = System.currentTimeMillis();
            MToast.getInstance().setText("再按一下退出");
        } else if (mLastReadyBackgroundTimeStamp != 0) {
            //保存用来保存统计数据
            UMenUtils.onKillProcess();
            mLastReadyBackgroundTimeStamp = 0;
        }
    }

    List<String> tabTags = new ArrayList<>(4);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
        getTabHost().getTabWidget().setDividerDrawable(null);
        tabTags.add("main_tab_faxian");
        tabTags.add("main_tab_youke");
        tabTags.add("main_tab_zhailu");
        tabTags.add("main_tab_jiaoxue");

        addTab(tabTags.get(0), "发现", R.drawable.main_tab_faxian_sl, FaxianActivity.class.getName());
        addTab(tabTags.get(1), "优课", R.drawable.main_tab_youxue_sl, YoukeActivity.class.getName());
        addTab(tabTags.get(2), "摘录", R.drawable.main_tab_zailu_sl, ZhaiLuActivity.class.getName());
        addTab(tabTags.get(3), "教学", R.drawable.main_tab_jiaoxue_sl, JiaoXueActivity.class.getName());
        Intent intent = getIntent();
        parseIntent(intent, true);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        parseIntent(intent, false);
    }

    /**
     * 解析intent
     *
     * @param intent     intent
     * @param fromCreate 是否来至onCreate函数,即第一次启动MainActivity
     */
    private void parseIntent(Intent intent, boolean fromCreate) {
        if (intent == null) {
            return;
        }

        /** open url */
        openUrl(parse(intent), fromCreate);
    }

    private String parse(Intent intent) {
        /** MainFragment页面存在的时候调用MainFragment.onNewIntent传入新intent */
        String url = parseInternal(intent);
        if (StringUtils.isNotEmpty(url)) {
            return url;
        }

        /** 由push或外部浏览器或闪屏点击到达这的处理 */
        url = parseExternal(intent);
        if (StringUtils.isNotEmpty(url)) {
            return url;
        }
        return "";
    }

    private String parseInternal(Intent intent) {
        if (intent == null) {
            return "";
        }
        return intent.getStringExtra(Navigator.PARAM_ORIGIN_URL);
    }

    private String parseExternal(Intent intent) {
        if (intent == null) {
            return "";
        }
        Uri uri = intent.getData();
        if (uri != null) {
            return uri.toString();
        }
        return "";
    }

    /**
     * launch page url
     *
     * @param schemeUrl  url
     * @param fromCreate 是否来至onCreate函数,即第一次启动MainActivity
     */
    private boolean openUrl(String schemeUrl, boolean fromCreate) {
        if (StringUtils.isEmpty(schemeUrl)) {
            return false;
        }

        String url = schemeUrl;
        if (schemeUrl.startsWith("teachin://page/main_lancher")) {

            Uri uri = Uri.parse(schemeUrl);
            url = uri.getQueryParameter("url");
            if (TextUtils.isEmpty(url)) {
                return false;
            }
        }

        Uri uri = Uri.parse(url);
        List<String> pathList = uri.getPathSegments();
        if (pathList != null && pathList.size() > 0) {
            String firstPath = pathList.get(0);
            int position = tabTags.indexOf(firstPath);
            if (position >= 0) {
                getTabHost().setCurrentTab(position);
                return true;
            }
        }

        return new Navigator.Builder()
            .withUrl(url)
            .build()
            .open();
    }

    /**
     * 创建tab
     *
     * @param title title
     * @param icon  icon
     */
    private void addTab(String tabId, String title, int icon, String activityClassName) {
        addTab(tabId, title, icon, activityClassName, false);
    }

    private void addTab(String tabId, String title, int icon, Intent intent) {
        TabHost.TabSpec tabSpec = getTabHost().newTabSpec(tabId)
            .setIndicator(getTabItemView(title, icon))
            .setContent(intent);
        try {
            getTabHost().addTab(tabSpec);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void addTab(String tabId, String title, int icon, String activityClassName, boolean empty) {
        TabHost.TabSpec tabSpec = getTabHost().newTabSpec(tabId)
            .setIndicator(empty ? new View(this) : getTabItemView(title, icon))
            .setContent(new Intent().setClassName(this, activityClassName));
        getTabHost().addTab(tabSpec);
    }

    private View getTabItemView(String title, @DrawableRes int icon) {
        View view = LayoutInflater.from(this).inflate(R.layout.main_tab_layout, null);
        ImageView iconTextView = (ImageView)view.findViewById(R.id.tab_icon);
        TextView textView = (TextView)view.findViewById(R.id.tab_title);
        iconTextView.setImageResource(icon);
        textView.setText(title);
        return view;
    }
}
